package com.ncs.nc.mq;

import com.google.gson.Gson;
import com.ncs.nc.entity.RabbitDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 创建一个用于生产，发送消息的生产者RabbitSender,
 * 并在其中创建一方法用于生产消息，将消息发送至前文定义好的RabbitMQ消息模型中，
 */
@Component
public class RabbitSender {
    private static final Logger log= LoggerFactory.getLogger(RabbitSender.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private Environment env;

    //发送消息
    public void sendMsg(){
        RabbitDto dto=new RabbitDto(1,"双11大促销","这是双12大促销的具体详细内容~~~");
        //转化为消息
        String msg=new Gson().toJson(dto);
        //发送消息：指定交换器，路由键，队列
        Message message= MessageBuilder.withBody(msg.getBytes()).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        rabbitTemplate.setExchange((env.getProperty("mq.simple.exchange")));
        rabbitTemplate.setRoutingKey(env.getProperty("mq.simple.routing.key"));
        rabbitTemplate.send(message);
        log.info("RabbitMQ发送简单的消息成功~~~");
    }
}
